package com.lyw.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.lyw.common.to.SkuEsModel;
import com.lyw.gulimall.search.config.GulimallElasticSearchConfiguration;
import com.lyw.gulimall.search.constant.EsConstant;
import com.lyw.gulimall.search.service.ElasticSearchSaveService;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ElasticSearchSaveServiceImpl implements ElasticSearchSaveService {

    public static final Logger log = LoggerFactory.getLogger(ElasticSearchSaveServiceImpl.class);

    @Autowired
    private RestHighLevelClient client;

    @Override
    public void productStatusUp(List<SkuEsModel> skuEsModels) {

        // 2、给 ES 保存数据
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModels.forEach(item -> {
            // 1、在 ES 建立索引
            // 构造一个 ES 的保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 保存 id
            indexRequest.id(item.getSkuId().toString());

            // 以 json 的格式保存数据
            String jsonString = JSON.toJSONString(item);
            indexRequest.source(jsonString, XContentType.JSON);

            // 添加到批量操作中
            bulkRequest.add(indexRequest);
        });

        client.bulkAsync(bulkRequest, GulimallElasticSearchConfiguration.COMMON_OPTIONS, new ActionListener<BulkResponse>(){
            @Override
            public void onResponse(BulkResponse bulkItemResponses) {
                log.info(LocalDateTime.now().toString() + "：数据添加成功........");
            }
            public void onFailure(Exception e) {

                // TODO 批量错误需要处理
                log.error(LocalDateTime.now().toString() + "：数据添加失败，失败原因：{}", e);
            }
        });
    }
}
